import React from 'react';
import L from 'leaflet';
import {
  Marker, withLeaflet, Popup
} from 'react-leaflet';
import { isEqual, without } from 'lodash';
import classNames from 'classnames/bind';
import { isLngLat } from 'src/util/mapUtil';
import styles from './index.less';
import setting from './setting';
import { getHrefSearch } from './location';
import defaultImageIcon from './image/local.png';

const classes = classNames.bind(styles);
const urlSearchParams = getHrefSearch();

// 三种方式的弹出框
const popupStyles = {
  selected: {
    background: 'rgb(29,25,20)',
    border: '2px solid rgba(255,255,28,0.65)',
    borderRadius: '4px',
    boxShadow: '0px 2px 20px 0px #000,0px 2px 20px 0px rgba(255,255,31,0.54)',
    fontSize: '20px',
    color: 'rgb(232,204,130)'
  }
};
class LCompare extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      realData: [],
      selectedMarker: [],
      isOpenAnalysis: false
    };
    this.setDataPool({ id: '' });
    this.updateEventsDefaultValue({ id: '' });
  }

  componentWillReceiveProps(nextProps) {
    const { data } = this.props;
    const { data: nextData } = nextProps;

    if (!isEqual(data, nextData)) {
      const { mapper } = nextProps.events.click.fields.id;
      const id = urlSearchParams[mapper] || '';
      const selectedMarker = [];
      if (id && nextData.find((item) => item.id === id)) {
        selectedMarker.push(id);
      }
      this.setState({ realData: nextData, selectedMarker });
      this.setDataPool({ id: selectedMarker.join() });
      this.updateEventsDefaultValue({ id: selectedMarker.join() });
    }
  }


  static setting = setting;

  // 获得图片icon
  getImageIcon = (info, imageUrl, isSelected) => {
    const {
      config: { default: { top, left } }
    } = this.props;
    const { selectedMarker } = this.state;
    const isForget = selectedMarker.length === 2;


    const iconAnchor = [left, top];
    if (isSelected) {
      return L.icon({
        className: 'noBackground',
        iconUrl: imageUrl || defaultImageIcon,
        iconAnchor
      });
    }

    return L.divIcon({
      className: 'noBackground analysisDivIcon',
      html: `<img src="${imageUrl || defaultImageIcon}" class="analysisImg"/>
            <div class="${isForget ? 'forget' : 'analysisNormal'}">${info}</div>`,
      iconAnchor
    });
  };

  // 获得弹出框文本
  getPopupContext = (info, type) => {
    const infoArray = `${info}`.split(';');
    return (<section
      className="map-marker-content"
      style={popupStyles[type]}
    >
      {infoArray.map((item, idx) =>
        (<React.Fragment key={`line${idx}`}>
          {item}
          <br />
        </React.Fragment>))
      }
    </section>);
  };

  onClosePopup = (id) => {
    const { selectedMarker } = this.state;
    if (!selectedMarker.includes(id)) return;
    const newSelectedMarkers = without(selectedMarker, id);

    this.setDataPool({ id: newSelectedMarkers.join() });
    this.setState({
      selectedMarker: newSelectedMarkers
    });
  }

  getMarker = (lng, lat, url, info, value, id, index) => {
    const {
      config: {
        default: {
          normalImg, selectImg, forgetImg, selectImg2
        }
      }
    } = this.props;
    const { selectedMarker, visible } = this.state;
    const isSelected = selectedMarker.includes(id);
    let imgUrl = '';

    if (isSelected) {
      imgUrl = selectedMarker.indexOf(id) === 0 ? selectImg : selectImg2;
    } else {
      imgUrl = selectedMarker.length === 2 ? forgetImg : normalImg;
    }

    const imageIcon = this.getImageIcon(info, imgUrl, isSelected);
    return (<Marker
      key={`popup${index}${lat}${visible}`}
      position={[lat, lng]}
      icon={imageIcon}
      onClick={() => this.onClickMarker(id, url)}
    >
      <Popup
        position={[lat, lng]}
        direction="right"
        className="marker-popup"
        closeButton
        autoClose={false}
        closeOnClick={false}
        onClose={() => this.onClosePopup(id)}
        offset={[10, -10]}
      >
        {this.getPopupContext(info, 'selected')}
      </Popup>
    </Marker>);
  };

  onClickMarker = (id, url) => {
    const { selectedMarker, isOpenAnalysis } = this.state;

    if (!isOpenAnalysis && url) {
      window.location.href = `${url}&id=${id}`;
      return;
    }

    if (selectedMarker.includes(id)) return;
    if (selectedMarker.length < 2) {
      const newSelectMarker = Array.from(selectedMarker);
      newSelectMarker.push(id);

      this.setDataPool({ id: newSelectMarker.join() });

      this.setState({
        selectedMarker: newSelectMarker
      });
    }
  };

  // 更新store中的dataPoll
  setDataPool(dataPoll) {
    const {
      bigScreen: { setDataPool }, editable,
      events: { click },
      path
    } = this.props;
    setDataPool(click, dataPoll, path, editable);
  }

  // 更新交互事件绑定的默认值
  updateEventsDefaultValue(dataPoll) {
    const {
      bigScreen: { updateEventsDefaultValue }, path, editable
    } = this.props;
    if (!editable) return;
    const eventValues = Object.keys(dataPoll).reduce(
      (pre, key) => Object.assign(pre,
        { [`click.fields.${key}.value`]: dataPoll[key] }), {}
    );
    updateEventsDefaultValue(path, eventValues);
  }

  showDialog = () => {
    const { selectedMarker } = this.state;
    const { config: { dataConfig: { screenUrl } } } = this.props;

    const urlList = screenUrl.split('$');
    const finalUrl = `${urlList[0]}${selectedMarker[0]}&${urlList[1]}${selectedMarker[1]}`;

    window.location.href = finalUrl;
    this.setState({ selectedMarker: [] });
  }

  render() {
    const {
      realData, selectedMarker, isOpenAnalysis,
    } = this.state;

    const selectedData = selectedMarker.map(
      (select) => realData.filter((item) => select === item.id).pop()
    );

    return (
      <React.Fragment>
        {realData.filter(({ lng, lat }) => isLngLat(lng, lat))
          .map(({
            lng, lat, value = 1, url, info, id = ''
          }, index) => this.getMarker(
            lng, lat, url, info, value, id, index
          ))}
        {selectedMarker.length === 2 && <div>
          <div className={classes('areaWrap')}>
            <div className={classes('mask')}></div>
            <div className={classes('names')}>
              <div className={classes('name')}>
                {!!selectedData[0] && selectedData[0].info}
              </div>
              <div className={classes('plus')}>+</div>
              <div className={classes('name')}>
                {!!selectedData[1] && selectedData[1].info}
              </div>
            </div>
            <div
              className={classes('compareAnalysis')}
              onClick={this.showDialog}
            >
              对比分析
            </div>
          </div>
        </div>}
        <div
          className={classes('openButton')}
          onClick={() => this.setState({ isOpenAnalysis: !isOpenAnalysis })}
        >
          {!isOpenAnalysis ? '分析' : '关闭分析'}
        </div>
      </React.Fragment>
    );
  }
}

export default withLeaflet(LCompare);
